import { defineStore } from 'pinia'
import router from '@/router/index'
import { store } from '../index'
interface TagsViewState {
  activeTabsValue: string,
  visitedViews: AppRouteRecordRaw[],
}
export const useTagsViewStore = defineStore('tagsViewState', {
  state: (): TagsViewState => ({
    activeTabsValue: '/home',
    visitedViews: [],
  }),
  getters: {},
  actions: {
    setTabsMenuValue(val: string) {
      this.activeTabsValue = val
    },
    addView(view: AppRouteRecordRaw) {
      this.addVisitedView(view)
    },
    addVisitedView(view: AppRouteRecordRaw) {
      if (typeof view.path === 'string') this.setTabsMenuValue(view.path)
      if (view.meta.noTagsView) return
      if (this.visitedViews.some((v) => v.path === view.path)) return
      this.visitedViews.push(
        Object.assign({}, view, {
          title: view.meta.title || 'no-name',
        }),
      )
    },
    delView(activeTabPath: string) {
      return new Promise((resolve) => {
        this.delVisitedView(activeTabPath)
        resolve({
          visitedViews: [...this.visitedViews],
        })
      })
    },
    toLastView(activeTabPath: string) {
      const index = this.visitedViews.findIndex((item) => item.path === activeTabPath)
      const nextTab = this.visitedViews[index + 1] || this.visitedViews[index - 1]
      if (!nextTab) return
      router.push({ path: nextTab.path })
      this.addVisitedView(nextTab)
    },
    delVisitedView(path: string) {
      return new Promise((resolve) => {
        this.visitedViews = this.visitedViews.filter((v) => {
          return v.path !== path || v.meta.affix
        })
        resolve([...this.visitedViews])
      })
    },
    clearVisitedView() {
      this.delAllViews()
    },
    delAllViews() {
      return new Promise((resolve) => {
        this.visitedViews = this.visitedViews.filter((v) => v.meta.affix)
        resolve([...this.visitedViews])
      })
    },
    delOtherViews(path: string) {
      this.visitedViews = this.visitedViews.filter((item) => {
        return item.path === path || item.meta.affix || item.path === '/home/index'
      })
    },
    goHome() {
      this.activeTabsValue = '/home'
      router.push({ path: '/home' })
    },
  },
})
export const useTagsViewStoreStoreWithOut = () => {
  return useTagsViewStore(store)
}
